<template>
  <MySplitPanes>
    <pane>
      <div class="my-flex-column w100 h100">
        <el-card v-show="state.showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
          <el-form :inline="true" label-width="auto" @submit.stop.prevent>
            <el-form-item>
              <my-select-input v-model="state.pageInput.dynamicFilter" :filters="state.filters" @search="onQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
              <el-button type="primary" icon="ele-Search" @click="onFilter"> 高级查询 </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="my-fill mt8" shadow="never">
          <div class="my-tools-box mb8 my-flex my-flex-between">
            <div>
              <el-button v-auth="'api:industry:production-line:add'" type="primary" icon="ele-Plus" @click="onAdd"> 新增
              </el-button>
            </div>
            <div>
              <el-tooltip effect="dark" :content="state.showQuery ? '隐藏查询' : '显示查询'" placement="top">
                <el-button :icon="state.showQuery ? 'ele-ArrowUp' : 'ele-ArrowDown'" circle
                  @click="state.showQuery = !state.showQuery" />
              </el-tooltip>
            </div>
          </div>

          <el-table ref="tableRef" v-loading="state.loading" :data="state.productionLineListData" row-key="id" border>
            <el-table-column type="selection" />
            <el-table-column prop="lineCode" label="代号" width="100" show-overflow-tooltip />
            <el-table-column prop="lineName" label="名称" width="100" show-overflow-tooltip />
            <el-table-column prop="lineType" label="类型" width="100" show-overflow-tooltip />
            <el-table-column label="状态" width="80" align="center" fixed="right">
              <template #default="{ row }">
                <el-switch v-if="auth('api:industry:production-line:set-enable')" v-model="row.enabled"
                  :loading="row.loading" :active-value='true' :inactive-value='false' inline-prompt active-text="开启"
                  inactive-text="关闭" :before-change="() => onSetEnable(row)" />
                <template v-else>
                  <el-tag type="success" v-if="row.enabled">启用</el-tag>
                  <el-tag type="danger" v-else>禁用</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="capacity" label="生产能力(件/小时)" width="140" show-overflow-tooltip />
            <el-table-column prop="shiftDuration" label="班次时长" width="85" show-overflow-tooltip />
            <el-table-column prop="workHours" label="周时长" width="70" show-overflow-tooltip />
            <el-table-column prop="shiftCount" label="班次数量" width="85" show-overflow-tooltip />
            <el-table-column prop="startTime" label="开始时间" :formatter="formatterTime" width="160"
              show-overflow-tooltip />
            <el-table-column prop="endTime" label="停止时间" :formatter="formatterTime" width="160" show-overflow-tooltip />
            <el-table-column prop="location" label="位置" width="100" show-overflow-tooltip />
            <el-table-column prop="equipmentList" label="设备清单" width="100" show-overflow-tooltip />
            <el-table-column prop="processFlow" label="工艺流程" width="100" show-overflow-tooltip />
            <el-table-column prop="remarks" label="备注" width="100" show-overflow-tooltip />
            <el-table-column label="操作" width="140" header-align="center" align="center" fixed="right">
              <template #default="{ row }">
                <el-button v-auth="'api:industry:production-line:update'" icon="ele-EditPen" size="small" text
                  type="primary" @click="onEdit(row)">编辑</el-button>
                <my-dropdown-more v-auths="['api:industry:production-line:soft-delete']">
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-if="auth('api:industry:production-line:soft-delete')"
                        @click="onDelete(row)">删除产线</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </my-dropdown-more>
              </template>
            </el-table-column>
          </el-table>
          <div class="my-flex my-flex-end" style="margin-top: 10px">
            <el-pagination v-model:currentPage="state.pageInput.currentPage"
              v-model:page-size="state.pageInput.pageSize" :total="state.total" :page-sizes="[10, 20, 50, 100]" small
              background @size-change="onSizeChange" @current-change="onCurrentChange"
              layout="total, sizes, prev, pager, next, jumper" />
          </div>
        </el-card>
        <production-line-form ref="productionLineFormRef" :title="state.productionLineFormTitle"></production-line-form>
        <MyFilterDialog ref="myFilterDialogRef" :fields="state.filters" @sure="onFilterSure"></MyFilterDialog>
      </div>
    </pane>
  </MySplitPanes>
</template>
<script lang="ts" setup name="industry/productionLine">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent } from 'vue'
import { PageInputProductionLineGetPageInput, ProductionLineGetPageOutput, ProductionLineGetOutput } from '/@/api/industry/data-contracts'
import { ProductionLineApi } from '/@/api/industry/ProductionLine'
import { Pane } from 'splitpanes'
import dayjs from 'dayjs'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'
import { ElTable } from 'element-plus'

const ProductionLineForm = defineAsyncComponent(() => import('./compoents/production-line-form.vue'))
const MySplitPanes = defineAsyncComponent(() => import('/@/components/my-layout/split-panes.vue'))
const MySelectInput = defineAsyncComponent(() => import('/@/components/my-select-input/index.vue'))
const MyDropdownMore = defineAsyncComponent(() => import('/@/components/my-dropdown-more/index.vue'))
const MyFilterDialog = defineAsyncComponent(() => import('/@/components/my-filter/dialog.vue'))

const { proxy } = getCurrentInstance() as any

const productionLineFormRef = ref()
const myFilterDialogRef = ref();
const state = reactive({
  loading: false,
  showQuery: true,
  productionLineFormTitle: '',
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
    filter: {},
    dynamicFilter: {},
  } as PageInputProductionLineGetPageInput,
  productionLineListData: [] as Array<ProductionLineGetPageOutput>,
  filters: [
    {
      field: 'lineCode',
      operator: 'Equal',
      description: '产线代号',
      componentName: 'el-input',
      defaultSelect: true,
    },
    {
      field: 'lineName',
      operator: 'Contains',
      description: '产线名称',
      componentName: 'el-input',
      defaultSelect: false,
    }
  ] as Array<DynamicFilterInfo>,
})
onMounted(async () => {
  await onQuery();
  eventBus.off('refreshProductionLine')
  eventBus.on('refreshProductionLine', async () => {
    onQuery()
  })
})
onBeforeMount(() => {
  eventBus.off('refreshProductionLine')
})
const formatterTime = (row: any, column: any, cellValue: any) => {
  return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
}
//查询分页
const onQuery = async () => {
  state.loading = true
  const res = await new ProductionLineApi().getPage(state.pageInput).catch(() => {
    state.loading = false
  })

  state.productionLineListData = res?.data?.list ?? []
  state.total = res?.data?.total ?? 0
  state.loading = false
}
//高级查询
const onFilter = () => {
  myFilterDialogRef.value.open()
}

const onFilterSure = (dynamicFilter: any) => {
  state.pageInput.dynamicFilter = dynamicFilter
  onQuery()
}

//新增
const onAdd = () => {
  state.productionLineFormTitle = '新增产线信息'
  productionLineFormRef.value.open()
}

//修改
const onEdit = (row: ProductionLineGetOutput) => {
  state.productionLineFormTitle = '编辑产线信息'
  productionLineFormRef.value.open(row)
}

//删除
const onDelete = (row: ProductionLineGetOutput) => {
  proxy.$modal
    .confirmDelete(`确定要删除产线代号为【${row.lineCode}】?`)
    .then(async () => {
      await new ProductionLineApi().softDelete({ id: row.id }, { loading: true, showSuccessMessage: true })
      onQuery()
    })
    .catch(() => { })
}
//启用或禁用
const onSetEnable = (row: ProductionLineGetOutput & { loading: boolean }) => {
  return new Promise((resolve, reject) => {
    proxy.$modal
      .confirm(`确定要${row.enabled ? '禁用' : '启用'}产线代号为：【${row.lineCode}】?`)
      .then(async () => {
        row.loading = true
        const res = await new ProductionLineApi()
          .setEnable({ productLineId: row.id, enabled: !row.enabled }, { showSuccessMessage: true })
          .catch(() => {
            reject(new Error('Error'))
          })
          .finally(() => {
            row.loading = false
          })
        if (res && res.success) {
          resolve(true)
        } else {
          reject(new Error('Cancel'))
        }
      })
      .catch(() => {
        reject(new Error('Cancel'))
      })
  })
}
const onSizeChange = (val: number) => {
  state.pageInput.currentPage = 1
  state.pageInput.pageSize = val
  onQuery()
}

const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  onQuery()
}
</script>
<style scoped lang="scss"></style>
